//
//  LoginVC.m
//  IkongWuProgram
//
//  Created by 徐益智 on 16/2/16.
//  Copyright © 2016年 Vdianjing. All rights reserved.
//

#import "LoginVC.h"
#import "AppDelegate.h"

#import "Header.h"
#import "MarkHeader.h"

#import "UIButton+WebCache.h"

#import "UserModel.h"
#import "ChatHelper.h"

#define kHeaderImageTag 100001
#define kNameLabelTag 200001

@interface LoginVC ()
{
    __block NSTimer *_timer;
    __block NSInteger _secondsCountDown;
}

@property (nonatomic, weak)UITextField *phoneTextField;
@property (nonatomic, weak)UITextField *codeTextField;
@property (nonatomic, weak)UIButton *sendCodeBtn;
@property (nonatomic, weak)UIButton *loginBtn;

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"登陆";
    self.view.backgroundColor = kWhiteColor;
    
    [self initBody];
}

- (void)initBody
{
    UIView *contentView = self.view;
    CGFloat org = 10;
    
    // 自定义导航栏
    UIView *navView = [[UIView alloc] init];
    navView.backgroundColor = kNavBackgroundColor;
    navView.frame = CGRectMake(0, 0, kScreenWidth, 64);
    [contentView addSubview:navView];
    
//    UIButton *backButton = [UIButton buttonWithFont:0 withTextColor:[UIColor clearColor] withBackgroundColor:[UIColor clearColor] withText:@""];
//    backButton.frame = CGRectMake(20, 20, 10, 44);
//    [backButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
//    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//    [navView addSubview:backButton];
    
    UILabel *title = [UILabel labelWithFont:14 withTextColor:kWhiteColor withBackgroundColor:[UIColor clearColor] withTextAlignment:NSTextAlignmentCenter withText:@"登录" withNumberLines:1];
    title.frame = CGRectMake(0, 20, kScreenWidth, 44);
    [navView addSubview:title];
    
    // logo 图片
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.bounds = CGRectMake(0, 0, 224, 28);
    imageV.center = CGPointMake(kScreenWidth / 2.0, 28/2.0 + 40 + 64);
    imageV.image = [UIImage imageNamed:@"login_maide"];
    [contentView addSubview:imageV];
    
    // 手机号 view
    UIView *phoneView = [[UIView alloc] init];
    [contentView addSubview:phoneView];
    phoneView.sd_layout
    .leftSpaceToView(contentView, kMargin)
    .rightSpaceToView(contentView, kMargin)
    .topSpaceToView (imageV, 40)
    .heightIs(45);
    
    phoneView.layer.cornerRadius = kRadiusCorner;
    phoneView.layer.masksToBounds = YES;
    phoneView.layer.borderColor = kGrayFontColor.CGColor;
    phoneView.layer.borderWidth = 1.f;
    
    
    UIImageView *phoneImage = [[UIImageView alloc] init];
    phoneImage.image = [UIImage imageNamed:@"study_nor"];
    [phoneView addSubview:phoneImage];
    phoneImage.sd_layout
    .leftSpaceToView(phoneView, org)
    .topSpaceToView(phoneView, 15/2.0)
    .widthIs(30)
    .heightIs(30);
    
    UITextField *phoneTextField = [UITextField textFieldWithFont:15.f withTextColor:kGetColor(198, 199, 204) withBackgroundColor:kWhiteColor withKeyBoardType:UIKeyboardTypeNumberPad withEextAlignment:NSTextAlignmentLeft withClearButtonMode:UITextFieldViewModeWhileEditing withText:@"" withPlaceholder:@"手机号" withPlaceholderTextColor:kGetColor(198, 199, 204)];
    [phoneView addSubview:phoneTextField];
    self.phoneTextField = phoneTextField;
    phoneTextField.sd_layout
    .leftSpaceToView(phoneImage, org)
    .rightSpaceToView(phoneView, org)
    .topEqualToView(phoneView)
    .heightIs(45);
    
    // 验证码 view
    UIView *codeView = [[UIView alloc] init];
    [contentView addSubview:codeView];
    
    // code view
    codeView.sd_layout
    .topSpaceToView(phoneView, 20)
    .leftSpaceToView(contentView, kMargin)
    .rightSpaceToView(contentView, (kMargin + 90 + org))
    .heightIs(45);
    
    codeView.layer.cornerRadius = kRadiusCorner;
    codeView.layer.masksToBounds = YES;
    codeView.layer.borderColor = kGrayFontColor.CGColor;
    codeView.layer.borderWidth = 1.f;
    
    
    UIImageView *codeImage = [[UIImageView alloc] init];
    codeImage.image = [UIImage imageNamed:@"key_image"];
    [codeView addSubview:codeImage];
    codeImage.sd_layout
    .leftSpaceToView(codeView, org)
    .topSpaceToView(codeView, 15/2.0)
    .widthIs(30)
    .heightIs(30);
    
    UITextField *codeTextField = [UITextField textFieldWithFont:15.f withTextColor:kGetColor(198, 199, 204) withBackgroundColor:kWhiteColor withKeyBoardType:UIKeyboardTypeNumberPad withEextAlignment:NSTextAlignmentLeft withClearButtonMode:UITextFieldViewModeWhileEditing withText:@"" withPlaceholder:@"动态密码" withPlaceholderTextColor:kGetColor(198, 199, 204)];
    [codeView addSubview:codeTextField];
    self.codeTextField = codeTextField;
    codeTextField.sd_layout
    .leftSpaceToView(codeImage, org)
    .topEqualToView(codeView)
    .rightSpaceToView(codeView, org)
    .heightIs(45);
    
    // 发送 code 按钮
    UIButton *sendCodeBtn = [UIButton buttonWithFont:14 withTextColor:[UIColor whiteColor] withBackgroundColor:kLightYellowColor withText:@"获取验证码"];
    [sendCodeBtn addTarget:self action:@selector(sendCode:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:sendCodeBtn];
    self.sendCodeBtn = sendCodeBtn;
    sendCodeBtn.sd_layout
    .leftSpaceToView(codeView, org)
    .topEqualToView(codeView)
    .widthIs(90)
    .heightIs(45);
    sendCodeBtn.layer.cornerRadius = kRadiusCorner;
    sendCodeBtn.layer.masksToBounds = YES;
    
    
    
    UIButton *loginBtn = [UIButton buttonWithFont:14 withTextColor:[UIColor whiteColor] withBackgroundColor:kLightYellowColor withText:@"登录"];
    [loginBtn addTarget:self action:@selector(loginBtn:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:loginBtn];
    self.loginBtn = loginBtn;
    loginBtn.sd_layout
    .leftSpaceToView(contentView, kMargin)
    .topSpaceToView (codeView, kMargin)
    .rightSpaceToView(contentView, kMargin)
    .heightIs(45);
    loginBtn.layer.cornerRadius = kRadiusCorner;
    loginBtn.layer.masksToBounds = YES;
}

- (void)backButton
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendCode:(UIButton *)sender
{
    self.sendCodeBtn.enabled = NO;
    [self loadCodeData];
}

- (void)initTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    _secondsCountDown = 60;//60秒倒计时
}

//倒计时方法验证码实现倒计时60秒，60秒后按钮变换开始的样子
-(void)timerFireMethod:(NSTimer *)theTimer
{
    if (_secondsCountDown == 1) {
        [theTimer invalidate];
        _secondsCountDown = 60;
        [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.sendCodeBtn setEnabled:YES];
    }else{
        _secondsCountDown--;
        NSString *title = [NSString stringWithFormat:@"(%ld)重新获取",(long)_secondsCountDown];
        [self.sendCodeBtn setTitle:title forState:UIControlStateNormal];
    }
}

#pragma mark - load data
- (void)loadCodeData
{
    if (self.phoneTextField.text.length == 0) {
        [JQProgressHUD showErrorMessage:@"手机号码不能为空"];
        return;
    }
    
    kWeakSelf
    
    SEObject *object = [SEObject objectWithClassName:@"login"];
    
    [object setObject:@"getLoginCode" forKey:@"action"];
    [object setObject:self.phoneTextField.text forKey:@"mobile"];
    //  "app_version":"teacher"
    [object setObject:@"teacher" forKey:@"app_version"];
    
    [SGProgressHUD show:@"加载中..."];
    [object saveInbackgroundOnSuccess:^(SEObject *object) {
        [SGProgressHUD dismiss];
        [weakSelf initTimer];
        weakSelf.sendCodeBtn.enabled = NO;
    } onFailureBlock:^(NSError *error) {
        [SGProgressHUD dismiss];
        weakSelf.sendCodeBtn.enabled = YES;
        [_timer invalidate];
    }];
}

- (void)loginBtn:(UIButton *)sender
{
    if (self.phoneTextField.text.length == 0) {
        [JQProgressHUD showErrorMessage:@"手机号码不能为空"];
        return;
    }
    if (self.codeTextField.text.length == 0) {
        [JQProgressHUD showErrorMessage:@"验证码不能为空"];
        return;
    }
    
    [self loginWithUsername:@"17756234759" password:@"111111"];
    
    SEObject *object = [SEObject objectWithClassName:@"login"];
    [object setObject:@"loginByCode" forKey:@"action"];
    [object setObject:self.phoneTextField.text forKey:@"mobile"];
    [object setObject:self.codeTextField.text forKey:@"code"];
    [object setObject:@"teacher" forKey:@"app_version"];
    
    [SGProgressHUD show:@"加载中..."];
    [object saveInbackgroundOnSuccess:^(SEObject *object) {
        [SGProgressHUD dismiss];
        
        NSDictionary *items = [object objectForKey:@"items"];
        
        NSDictionary *dic = items[@"user_profile"];
        UserModel *model = [[UserModel alloc] init];
        model.uid = dic[@"uid"];
        model.mobile = dic[@"mobile"];
        model.username = dic[@"username"];
        model.nickname = dic[@"nickname"];
        model.avatar = dic[@"avatar"];
        model.token = dic[@"token"];
        model.account_type = dic[@"account_type"];
        if ([dic[@"sex"] isEqualToString:@"0"]) {
            model.sex = @"男";
        }else {
            model.sex = @"女";
        }
        model.truename = dic[@"truename"];
        model.user_type = dic[@"user_type"];
        model.group_type = dic[@"group_type"];
        model.password = dic[@"password"];
        model.hx_username = dic[@"hx_username"];
        [model save];
        
        [self loadData];
        [_timer invalidate];
        
//        [self loginWithUsername:model.hx_username password:@"mdfunk1564"];
        
    } onFailureBlock:^(NSError *error) {
        [SGProgressHUD dismiss];
        [_timer invalidate];
    }];
}

- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    //异步登陆账号
    [[EMClient sharedClient] asyncLoginWithUsername:username password:password success:^{
        
        //设置是否自动登录
        [[EMClient sharedClient].options setIsAutoLogin:YES];
        [[EMClient sharedClient] dataMigrationTo3];
        [[ChatHelper shareHelper] asyncPushOptions];
        
        //发送自动登陆状态通知
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
        
    } failure:^(EMError *aError) {
        switch (aError.code)
        {
            case EMErrorNetworkUnavailable:
                TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                break;
            case EMErrorServerNotReachable:
                TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                break;
            case EMErrorUserAuthenticationFailed:
                TTAlertNoTitle(aError.errorDescription);
                break;
            case EMErrorServerTimeout:
                TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                break;
            default:
                TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                break;
        }
    }];
}

- (void)loadData
{
    SEObject *object = [SEObject objectWithClassName:@"profile"];
    
    [object setObject:@"getPersonalProfile" forKey:@"action"];
    
    [SGProgressHUD show:@"加载中..."];
    [object saveInbackgroundWithHasHeader:YES OnSuccess:^(SEObject *object) {
        [SGProgressHUD dismiss];
        UserModel *model = [UserModel queryModel];
        
        NSDictionary *items = [object objectForKey:@"items"];
        NSDictionary *dic = items[@"user_info"];
        model.school_id = dic[@"school_id"];
        model.account_money = dic[@"account_money"];
        // "account_money":"10.00"
        [model save];
        
    } onFailureBlock:^(NSError *error) {
        [SGProgressHUD dismiss];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:NO];
}

@end
